/**
 * MineAdmin is committed to providing solutions for quickly building web applications
 * Please view the LICENSE file that was distributed with this source code,
 * For the full copyright and license information.
 * Thank you very much for using MineAdmin.
 *
 * @Author X.Mo<root@imoi.cn>
 * @Link   https://github.com/mineadmin
 */

import { useI18n } from 'vue-i18n'
import type { ComposerTranslation } from 'vue-i18n'
import { getCurrentInstance } from 'vue'

export interface TransType {
  globalTrans: ComposerTranslation
  localTrans: ComposerTranslation
}

// 使用 WeakMap 来缓存每个组件实例的 i18n 实例，避免重复调用
const i18nInstanceCache = new WeakMap()

export function useTrans(key: any | null = null): TransType | string | any {
  const instance = getCurrentInstance()
  
  let i18n
  if (instance && i18nInstanceCache.has(instance)) {
    // 如果当前组件实例已经有缓存的 i18n，直接使用
    i18n = i18nInstanceCache.get(instance)
  } else {
    // 创建新的 i18n 实例
    i18n = useI18n()
    // 如果有组件实例，缓存这个 i18n 实例
    if (instance) {
      i18nInstanceCache.set(instance, i18n)
    }
  }

  if (key === null) {
    return {
      localTrans: i18n.t,
      globalTrans: i18n.t,
    }
  }
  else {
    return i18n.te(key) ? i18n.t(key) : key
  }
}
